define([
  'underscore',
  'models/User',
  'views/View',
  'hbs!template/media/users-selectionNew'
], function(_,
            User, 
            View,
            template) {
  var UsersSelection = View.extend({
    template: template, // Default template
    
    // Events manage the selection.
    events: {
      "click a[name=add]":              "addDst",
      "click a[name=delete]":           "removeDst",
      "click button[name=send]":        "triggerSend"
    },

    initialize: function(options) {
      // Options object
      options || (options = {});

      // Call View's initialize method
      View.prototype.initialize.call(this, options);

      // If there is a template, set it.
      if(options.template) {
        this.template = options.template;
      }

      // If the user is not in options, create it.
      if(!options.model) {
        this.model = new User();
      }
      this.model.bind("change", this.getRelations, this);
      this.model.fetch();
      
      // Create an array to store the selected users.
      this.receivers = [];
    },

    triggerSend: function() {
      this.trigger("action:send");
    },
    
    getRelations: function() { // Handler that will be invoked when the model is loaded
      this.collection = this.model.get("isInternal") ? this.model.familiars : this.model.internals;
      // Bind reset event to the render handler.
      this.collection.bind("reset", this.render, this);
      // Loading...
      if(this.collection) {
        this.collection.bind("loading", this.showLoading, this);
      }
      // Fetch the users related to the current user.
      this.collection.fetch();
    },

    getReceivers: function() {
      return this.receivers;
    },
    
    render: function() {
      // Because of the collection is got when the model is loaded, if the collection doesn't exist yet, the view is not fully initialized.
      if(this.collection) {
        View.prototype.render.apply(this);
      }

      return this;
    },

    toggleShare: function() {
      if(this.flags.share) {
        this._sharing = !this._sharing;
        this.render();
      }
    },

    serialize: function() {
      // Get the data object from View.
      
      var data = {},
          users = [],
          that = this, // For iteration clousure.
          showSend = false; // Flag to show the send button
      if(this.collection) {
          // Pagination information.
        data.pagination = this.collection.pagination.info();
        
        // Users in json with selected flag.
        _.each(data.pagination.models, (function(user){
          var userData = {};
          if(that.receivers.indexOf(user) != -1) {
            userData.data = user.toJSON();
            showSend = true;
            userData.selected = true;
          } else {
            userData.data = user.toJSON();
            userData.selected = false;
          }
          users.push(userData);
        }));
      }

      // Put users into the data.
      data.users = users;

      // Put current user data. It will render different literals.
      data.user = this.model.toJSON();

      data._flags || (data._flags = {});
      data._flags.showSend = showSend;
      
      return data;
    },
    
    addDst: function(evt) { // Add a user to the selection handler
      var id = this._getDataId(evt),
      dst = this.collection.get(id);
      if(this.receivers.indexOf(dst) === -1) {
        this.receivers.push(dst);
        this.render();
      }
      this.trigger("update:selection", this.receivers); // Throw update:selection event
    },

    removeDst: function(evt) { // Remove a user to the selection handler
      var id = this._getDataId(evt),
      dst = this.collection.get(id),
      index = this.receivers.indexOf(dst);
      if(index !== -1) {
        this.receivers.splice(index, 1); // Remove the selected receiver.
        this.render();
      }
      this.trigger("update:selection", this.receivers); // Throw update:selection event
    },

    _getDataId: function(evt) { // Helper function to get the id from the click event.
      evt.preventDefault();
      var dataid =  this.$(evt.currentTarget).data("id");
      return dataid;
    }

  });

  return UsersSelection;
});